//
//  FujinViewController.m
//  Travel
//
//  Created by dllo on 15/12/3.
//  Copyright © 2015年 doll. All rights reserved.
//

#import "FujinViewController.h"
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>

@interface FujinViewController ()<MKMapViewDelegate, CLLocationManagerDelegate>

@property (nonatomic, retain) MKMapView *mapView;
@property (nonatomic, retain) CLLocationManager *manager;
@property (nonatomic, retain) CLLocation *location;
@property (nonatomic, retain) CLGeocoder *reocoder;
@property (nonatomic, retain) MKUserLocation *userLocation;
//接收每个大头针信息
@property (nonatomic, retain) NSMutableArray *annotationArr;

@property (nonatomic, strong) UISegmentedControl *segment;
@property (nonatomic, strong) NSArray *arr_items;

@property (nonatomic, assign) CLLocationCoordinate2D cll;
@property (nonatomic, assign) NSString *subtitle;

@end

@implementation FujinViewController

- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"leftBack"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(backToLast)];
    
    self.arr_items = @[@"餐厅", @"景点", @"住宿", @"购物"];
    self.segment = [[UISegmentedControl alloc] initWithItems:self.arr_items];
    self.segment.frame = CGRectMake(0, 0, 240, 30);
    self.navigationItem.titleView = self.segment;
    [self.segment addTarget:self action:@selector(searchPlace:) forControlEvents:UIControlEventValueChanged];
    
    //初始化大头针数组
    self.annotationArr = [NSMutableArray array];
    
    //初始化地图
    self.mapView = [[MKMapView alloc] initWithFrame:self.view.frame];
    [self.view addSubview:self.mapView];
    
    //mapView属性
    //代理
    self.mapView.delegate = self;
    //比例尺
    self.mapView.showsScale = YES;
    //指南针
    self.mapView.showsCompass = YES;
    //是新用户位置
    self.mapView.showsUserLocation = YES;
    //显示交通
    self.mapView.showsTraffic = YES;
    //跟踪模式
    self.mapView.userTrackingMode = MKUserTrackingModeFollow;
    //地图类型
    self.mapView.mapType = MKMapTypeStandard;
    
    
    //manager初始化
    self.manager = [[CLLocationManager alloc] init];
    [self.manager requestAlwaysAuthorization];
    //设置代理
    self.manager.delegate = self;
    //距离过滤
    self.manager.distanceFilter = 50;
    //定位精度
    self.manager.desiredAccuracy = kCLLocationAccuracyBest;
    //开始定位
    [self.manager startUpdatingLocation];
    
}

#pragma mark - 附近景点
- (void)searchPlace:(UISegmentedControl *)seg
{
    [self clearAction];
    
    NSString *search_name = self.arr_items[seg.selectedSegmentIndex];
    [self POIsearch:search_name];
}

- (void)clearAction
{
    //清除所有annotationView 清空annotationArr数组
    [self.mapView removeAnnotations:self.annotationArr];
    [self.annotationArr removeAllObjects];
}

- (void)POIsearch:(NSString *)queryName
{
    //本地搜索
    //搜索要发出请求,请求
    MKLocalSearchRequest *repuest = [[MKLocalSearchRequest alloc] init];
    //查找时的位置约束
    CLLocationCoordinate2D coordinate = self.location.coordinate;
    //查找范围约束
    //参数1:查找的中心点
    //参数2:经纬度跨度
    MKCoordinateSpan span = MKCoordinateSpanMake(0.1, 0.1);
    repuest.region = MKCoordinateRegionMake(coordinate, span);
    //关键字
    repuest.naturalLanguageQuery = queryName;
    MKLocalSearch *localSearch = [[MKLocalSearch alloc] initWithRequest:repuest];
    
    [localSearch startWithCompletionHandler:^(MKLocalSearchResponse * _Nullable response, NSError * _Nullable error) {
        
        if (error) {
            NSLog(@"本地搜索错误:%@", error);
        }else{
            for (MKMapItem *item in response.mapItems) {
                MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];
                annotation.title = item.name;
                annotation.subtitle = item.phoneNumber;
                
                MKPlacemark *placeMark = item.placemark;
                annotation.coordinate = placeMark.coordinate;
                [self.annotationArr addObject:annotation];
            }
            [self.mapView addAnnotations:self.annotationArr];
        }
        
    }];
    
}

#pragma mark - locationManager delegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    self.location = [locations lastObject];
    //NSLog(@"经纬度:%f %f", self.location.coordinate.latitude, self.location.coordinate.longitude);
    //NSLog(@"海拔:%f", self.location.altitude);
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd-hh:mm:ss";
    //NSString *dataStr = [formatter stringFromDate:self.location.timestamp];
    //NSLog(@"%@", dataStr);
    //NSLog(@"时间:%@", self.location.timestamp);
    [self reocoderMethod];
}

#pragma mark - 逆地理转换方法(将经纬度转化为国家,地区)
- (void)reocoderMethod
{
    self.reocoder = [[CLGeocoder alloc] init];
    
    //逆地理转换
    [self.reocoder reverseGeocodeLocation:self.location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (error == nil && placemarks.count > 0) {
            CLPlacemark *placeMark = placemarks.firstObject;

            
            self.mapView.userLocation.title = placeMark.locality;
            self.mapView.userLocation.subtitle = placeMark.addressDictionary[@"FormattedAddressLines"][0];
            
        }else if(error == nil && placemarks.count == 0){
            NSLog(@"没有返回结果");
        }else{
            NSLog(@"逆地理方法错误:%@", error);
        }
    }];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"定位失败的原因:%@", error);
}



//- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
//{
//    if ([annotation isKindOfClass:[MKPointAnnotation class]]) {
//        //大头针的创建类似于tabeView 都用到重用池  也可以不用,自己看内存.....
//        static NSString *string = @"annotation";
//        MKAnnotationView *annotationView = [self.mapView dequeueReusableAnnotationViewWithIdentifier:string];
//        
//        if (annotation == nil) {
//            annotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:string];
//        }
//        //其他属性自己看
//        annotationView.canShowCallout = YES;
//        //        //    annotationView.leftCalloutAccessoryView = self.calloutBtn;
//                UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
//        //        //    rightButton.tag = 2;
//                annotationView.rightCalloutAccessoryView = rightButton;
//        
//        return annotationView;
//        
//    } else {
//        
//        return nil;
//        
//    }
//    
//}

- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
{
    self.cll = view.annotation.coordinate;
    self.subtitle = view.annotation.subtitle;
    
    UIButton *btn_navi = [UIButton buttonWithType:UIButtonTypeSystem];
    btn_navi.frame = CGRectMake(WIDTH - 40, 50, 30, 30);
    //btn_navi.backgroundColor = [UIColor redColor];
    [btn_navi setImage:[UIImage imageNamed:@"go"] forState:UIControlStateNormal];
    [self.view addSubview:btn_navi];
    [btn_navi addTarget:self action:@selector(navi) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *btn_contact = [UIButton buttonWithType:UIButtonTypeSystem];
    btn_contact.frame = CGRectMake(WIDTH - 40, 50 + 10 + 30, 30, 30);
    [btn_contact setImage:[UIImage imageNamed:@"phone"] forState:UIControlStateNormal];
    //btn_contact.backgroundColor = [UIColor yellowColor];
    [self.view addSubview:btn_contact];
    [btn_contact addTarget:self action:@selector(contact) forControlEvents:UIControlEventTouchUpInside];

}

- (void)navi
{
    MKMapItem *currentLocation = [MKMapItem mapItemForCurrentLocation];
    MKMapItem *toLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:self.cll addressDictionary:nil]];

    [MKMapItem openMapsWithItems:@[currentLocation,toLocation] launchOptions:@{MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeDriving,MKLaunchOptionsShowsTrafficKey:[NSNumber numberWithBool:YES]}];
}

- (void)contact
{
    NSString *telStr = [NSString stringWithFormat:@"tel://%@", self.subtitle];
    NSURL *url = [NSURL URLWithString:telStr];
    if ([[UIApplication sharedApplication] canOpenURL:url]) {
        [[UIApplication sharedApplication] openURL:url];
    }
    else
    {
        UIAlertController *alert1 = [UIAlertController alertControllerWithTitle:@"提示" message:@"号码不可用\n或您的备设不支持拨号功能" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }];
        [alert1 addAction:okAction1];
        [self presentViewController:alert1 animated:YES completion:nil];
    }
}

#pragma mark - 自定义按钮触发方法 返回
- (void)backToLast
{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
